<?php

namespace Admin\Controller;

class SearchController extends AdminController {

    public function index() {
        $where = '1=1 ';

        $keywords = I('keywords');
        if ($keywords) {
            $where .= " and keywords like '%" . $keywords . "%'";
            $this->assign('keywords', $keywords);
        }

        $is_recmd = I('is_recmd', -1);
        $this->assign('is_recmd', $is_recmd);
        if ($is_recmd != -1) {
            $where .= ' and is_recmd =' . $is_recmd;
            $this->assign('is_recmd', $is_recmd);
        }

        $M = M('SearchKeywords');

        $field = '*';

        $order = "create_time desc";
        $list = $this->lists($M, $where, $order, $field);

        $this->assign('_list', $list);
        $this->assign('meta_title', '搜索关键字列表');
        $this->display();
    }

    public function add() {
        $id = I("id", 0, 'intval');
        if (IS_POST) {

            $data['keywords'] = I("title");
            $data['search_num'] = I("search_num", 0, 'intval');
            $data['update_time'] = date('Y-m-d H:i:s', time());

            if ($id == 0) {
                $res = M('SearchKeywords')->add($data);
            } else {
                $res = M('SearchKeywords')->where(array('key_id' => $id))->save($data);
            }

            if ($res) {
                $this->success('操作成功', U('index'));
            } else {
                $this->error('操作失败');
            }
        } else {
            $data = M('SearchKeywords')->where(array("key_id" => $id))->find();

            $this->assign('data', $data);
            $this->assign('meta_title', '新增/修改关键字');
            $this->display();
        }
    }

    public function del() {
        $id = I('id', 0, 'intval');
        if ($id == 0) {
            $this->error('错误的ID');
        }

        $res = M('SearchKeywords')->where(array('key_id' => $id))->delete();

        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    //推荐
    public function recmd() {
        $id = I('id', 0, 'intval');
        $status = I('s', 0, 'intval');

        $data = [];
        $data['is_recmd'] = $status;

        $res = M('SearchKeywords')->where(array('key_id' => $id))->save($data);

        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

}
